﻿using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Nes4Net.UI
{
    public class AudioWaveProvider : IWaveProvider, IDisposable
    {
        private const Int32 SAMPLE_COUNT = 16 * 1024;

        private Int32 audio_write_cursor = 0;
        private Int32 audio_read_cursor = 0;
        private Int32 SAMPLE_MASK = SAMPLE_COUNT - 1;
        private BufferedWaveProvider bufferedWaveProvider;

        public Action ReadCallBack { get; set; }


        public AudioWaveProvider() 
        {
            bufferedWaveProvider = new BufferedWaveProvider(new WaveFormat(44100, 16, 1));
            bufferedWaveProvider.DiscardOnBufferOverflow = true;
            bufferedWaveProvider.BufferLength = SAMPLE_COUNT;
        }

        public WaveFormat WaveFormat => bufferedWaveProvider.WaveFormat;

        public void Dispose()
        {

        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Write(Int32 l, Int32 r)
        {
            var buffss = new Byte[2];
            var buffsL = BitConverter.GetBytes(l);
            var buffsR = BitConverter.GetBytes(r);

            buffss[0] = buffsL[0];
            buffss[1] = buffsL[1];
            //buffss[2] = buffsR[0];
            //buffss[3] = buffsR[1];

            bufferedWaveProvider.AddSamples(buffss, 0, buffss.Length);
            audio_write_cursor = (audio_write_cursor + buffss.Length) & SAMPLE_MASK;
        }

        public int Read(byte[] buffer, int offset, int count)
        {
            var len = bufferedWaveProvider.Read(buffer, offset, count);
            audio_read_cursor = (audio_read_cursor + len) & SAMPLE_MASK;
            return len;
        }

        private int audio_remain()
        {
            return (audio_write_cursor - audio_read_cursor) & SAMPLE_MASK;
        }

        public Boolean CanFrame()
        {
            return audio_remain() < SAMPLE_COUNT;
        }
    }
}
